/*
 * Copyright (C) 2012 YIXIA.COM
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.vov.vitamio.activity;

import io.vov.vitamio.TVApplication;
import io.vov.vitamio.adapter.TVProgramsGridViewDescAdapter;
import io.vov.vitamio.entity.Online;
import io.vov.vitamio.entity.OnlineVideo;
import io.vov.vitamio.entity.OnlineVideoSource;
import io.vov.vitamio.entity.TVProgram;
import io.vov.vitamio.fragment.TVFragmentPagerAdapter;
import io.vov.vitamio.tvpaser.DateUtil;
import io.vov.vitamio.tvpaser.OnlineTVParser;
import io.vov.vitamio.tvpaser.StringUtil;
import io.vov.vitamio.tvpaser.XmlReaderHelper;
import io.vov.vitamio.utils.VP;
import io.vov.vitamio.widget.MediaController;
import io.vov.vitamio.widget.NDToast;
import io.vov.vitamio.widget.OutlineTextView;
import io.vov.vitamio.widget.SyncHorizontalScrollView;
import io.vov.vitamio.widget.VideoView;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.nio.ByteBuffer;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import net.simonvt.menudrawer.MenuDrawer;
import net.simonvt.menudrawer.MenuDrawer.OnDrawerStateChangeListener;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.KeyguardManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.j256.ormlite.stmt.QueryBuilder;
import com.naduolai.android.app.FlagUpdateManager;
import com.naduolai.android.net.DownloadManager;
import com.naduolai.android.net.Event;
import com.naduolai.android.net.TransferListener;
import com.ndjh.onlinetv.R;
import com.ndjh.ormlite.NDJHBaseDao;
import com.ndjh.stb.libsecurity;
import com.umeng.analytics.MobclickAgent;
import com.yixia.zi.provider.Session;
import com.yixia.zi.utils.BitmapHelper;
import com.yixia.zi.utils.DeviceUtils;
import com.yixia.zi.utils.FileHelper;
import com.yixia.zi.utils.FileUtils;
import com.yixia.zi.utils.Log;
import com.yixia.zi.utils.Media;
import com.yixia.zi.utils.StringHelper;
import com.yixia.zi.utils.ToastHelper;
import com.yixia.zi.utils.UIUtils;

@SuppressLint("HandlerLeak")
public class VideoActivity extends FragmentActivity implements MediaController.MediaPlayerControl, VideoView.SurfaceCallback {

	public static final int RESULT_FAILED = -7;

	private static final IntentFilter USER_PRESENT_FILTER = new IntentFilter(Intent.ACTION_USER_PRESENT);
	private static final IntentFilter SCREEN_FILTER = new IntentFilter(Intent.ACTION_SCREEN_ON);
	private static final IntentFilter HEADSET_FILTER = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
	private static final IntentFilter BATTERY_FILTER = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);

	private boolean mCreated = false;
	private boolean mNeedLock;
	private String mDisplayName;
	private String mBatteryLevel;
	private boolean mFromStart;
	private int mLoopCount;
	private boolean mSaveUri;
	private int mParentId;
	private float mStartPos;
	private boolean mEnd = false;
	private String mSubPath;
	private boolean mSubShown;
	private View mViewRoot;
	private VideoView mVideoView;
	private View mVideoLoadingLayout;
	private TextView mVideoLoadingText;
	private View mSubtitleContainer;
	private OutlineTextView mSubtitleText;
	private ImageView mSubtitleImage;
	private Uri mUri;
	private ScreenReceiver mScreenReceiver;
	private HeadsetPlugReceiver mHeadsetPlugReceiver;
	private UserPresentReceiver mUserPresentReceiver;
	private BatteryReceiver mBatteryReceiver;
	private boolean mReceiverRegistered = false;
	private boolean mHeadsetPlaying = false;
	private boolean mCloseComplete = false;
	private boolean mIsHWCodec = false;

	private MediaController mMediaController;
	private PlayerService vPlayer;
	private ServiceConnection vPlayerServiceConnection;
	private Animation mLoadingAnimation;
	private View mLoadingProgressView;
	private Session mSession;

	private MenuDrawer mMenuDrawer;

	private RelativeLayout mTvPrograms;
	public int ScreenWidth;
	public int ScreenHeight;

	private SyncHorizontalScrollView mTabList;

	private RelativeLayout mTabScroll;

	private RadioGroup mTabContent;

	private ViewPager mTabTVPager;

	private TVProgramsGridViewDescAdapter mTVProgramsListDescAdapter;
	// 左右导航箭头
	// private ImageView mTabLeft;
	// private ImageView mTabRight;

	public String[] mTabTitle = { "频道", "收藏"/*, "设置" */};

	private ArrayList<RadioButton> mTabPages = new ArrayList<RadioButton>();

	private GridView mTvProgramsGridview;

	private int mMenuWidth;

	private int mMenuHeight;

	private String mFirstPath;

	private String defaultpath = "http://180.153.91.28/data3/cdn_transfer/6B/93/6b199cd901d9d7fc4f7d4a88e925898720bacd93_1.flv?key=4dc228a2bce01256f219c00dcc44b07f&key1=1363590391";

	private NDJHBaseDao<OnlineVideo, Integer> onlineDao;
	private NDJHBaseDao<OnlineVideoSource, Integer> OnlineVideoSourceDao;
	private NDJHBaseDao<TVProgram, Integer> TVProgramsDao;

	private TVFragmentPagerAdapter mTabTVPagerAdapter;
	// 网速
	private String mDownloadRate = "";
	private int mVideoMode = VideoView.VIDEO_LAYOUT_STRETCH;

	public boolean mPlayerOK;

	private boolean mPlayerStop;
	private boolean OpenFailed = false;
//	private int mTempMode;
	private List<OnlineVideo> root;
	private boolean initPrograms = false;
	//当前位置
	private int mCurrentID = 1;

	private UIHandler uiHandler;

	private String mCurrentTitle = "";

	private TextView mTvProgramsTextView;
	private List<String> TVLinkList = new ArrayList<String>();
	// 网络已连接广播事件
	private static final String NETWORK_CONNECTION_ACTION = "com.naduolai.network.connection.action";
	// 网络断开广播事件
	private static final String NETWORK_DISCONNECTION_ACTION = "com.naduolai.network.disconnection.action";
	protected boolean mNetWorkConnectState = false;//网络状态标记

	private FragmentManager fm;
	
	/**
	 * 更新xml文件
	 */
	private String path = Environment.getExternalStorageDirectory().getPath();
	private String updateurl = "http://onlivetv.googlecode.com/svn/trunk/onlineupdate.xml";
	private SharedPreferences settings;
	private String CuttentDate = "0";
	private String dirpath = "";
	public static final String PREFS_NAME = "SettingPrefs";
	
	static {
		SCREEN_FILTER.addAction(Intent.ACTION_SCREEN_OFF);
	}

	@SuppressWarnings("unchecked")
	@SuppressLint("NewApi")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.e("VideoActivity onCreate");
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		
		if(!libsecurity.AuthorVerify()){
//			NDToast.makeTextShowFail(this, "认证不通过", 1000);
			if (UIUtils.hasICS()) {
//				android.os.Process.killProcess(android.os.Process.myPid());
			} else {
//				finish();
			}
		}
		if (!io.vov.vitamio.LibsChecker.checkVitamioLibs(this))
			return;
		MobclickAgent.setSessionContinueMillis(3 * 60000);
		checkUpgradeApk();// 检查应用版本
		
		mSession = new Session(this);
		vPlayerServiceConnection = new ServiceConnection() {
			@Override
			public void onServiceConnected(ComponentName name, IBinder service) {
				vPlayer = ((PlayerService.LocalBinder) service).getService();
				mServiceConnected = true;
				if (mSurfaceCreated)
					vPlayerHandler.sendEmptyMessage(OPEN_FILE);
			}

			@Override
			public void onServiceDisconnected(ComponentName name) {
				vPlayer = null;
				mServiceConnected = false;
			}
		};
		
		try {
			onlineDao = TVApplication.getInstance().getHelper().getDao(OnlineVideo.class);
			OnlineVideoSourceDao = TVApplication.getInstance().getHelper().getDao(OnlineVideoSource.class);
			TVProgramsDao = TVApplication.getInstance().getHelper().getDao(TVProgram.class);
			
			List<OnlineVideo> OnlineRoot = onlineDao.queryForAll();
			try {
				OnlineVideoSource OnlineVideoSourcedata = new OnlineVideoSource();
				
				dirpath  = Environment.getDataDirectory() + "/data/" + getPackageName() + "/files/" + "online.xml";
				File dirfile = new File(dirpath);
				if(!dirfile.exists() || !dirfile.canRead()){
					if(!copyFile("online.xml")){
						root = XmlReaderHelper.getAllVideos(this.getResources().getAssets().open("online.xml"));/*"online_1362967331818.xml"*/
					}else{
						root = XmlReaderHelper.getAllVideos(new FileInputStream(dirfile));/*"online_1362967331818.xml"*/
					}
				}else{
					root = XmlReaderHelper.getAllVideos(new FileInputStream(dirfile));/*"online_1362967331818.xml"*/
				}
					
				Log.e("数据库数量==>"+OnlineRoot.size());
				Log.e("xml数量==>"+root.size());
				if(root.size() <= 0){
					root = XmlReaderHelper.getAllVideos(this.getResources().getAssets().open("online.xml"));/*"online_1362967331818.xml"*/
				}
				if (OnlineRoot.size() <= 0 || (root.size() != OnlineRoot.size())) {
					// 需要更新数据
					onlineDao.deleteData("delete from 'OnlineVideo'");
					TVApplication.getInstance().getHelper().getWritableDatabase().execSQL("update sqlite_sequence SET seq = 0 where name = 'OnlineVideo'");
					uiHandler = new UIHandler(this);
					new AsyncTask<Object, Object, Boolean>() {
						

						@Override
						protected void onPreExecute() {
							initPrograms = true;
							Log.e("inited============start");
						}

						@Override
						protected Boolean doInBackground(Object... params) {
							try {
								OnlineVideoSource OnlineVideoSourcedata = new OnlineVideoSource();
								OnlineVideo OnlineVideodata = new OnlineVideo();
								for (int i = 0; i < root.size(); i++) {
									Log.e("inited============"+i);
									OnlineVideodata.setNum(root.get(i).getNum());
									OnlineVideodata.setSource_code(root.get(i).getSource_code());
									OnlineVideodata.setTitle(root.get(i).getTitle());
									OnlineVideodata.setVersion(root.get(i).getVersion());
									OnlineVideodata.setDesc(root.get(i).getDesc());
									OnlineVideodata.setIcon_url(root.get(i).getIcon_url());
									OnlineVideodata.setGuide(root.get(i).getGuide());
									OnlineVideodata.setCategoryId(root.get(i).getCategoryId());
									OnlineVideodata.setFavorite(false);
									onlineDao.create(OnlineVideodata);

									for (int x = 0; x < root.get(i).getSourceList().size(); x++) {
										OnlineVideoSourcedata.setSourcenum(root.get(i).getNum());
										OnlineVideoSourcedata.setLink(root.get(i).getSourceList().get(x).getLink());
										OnlineVideoSourcedata.setWidth(root.get(i).getSourceList().get(x).getWidth());
										OnlineVideoSourcedata.setHeight(root.get(i).getSourceList().get(x).getHeight());
										OnlineVideoSourcedata.setBitrate(root.get(i).getSourceList().get(x).getBitrate());
										OnlineVideoSourceDao.create(OnlineVideoSourcedata);
									}
								}
								return true;
							} catch (SQLException e) {
								e.printStackTrace();
							}
							return false;
						}

						@Override
						protected void onPostExecute(Boolean inited) {
							Log.e("inited============end"+inited);
							if (inited) {
								try {
			
									ArrayList<OnlineVideo> OldFavoriteList = TVApplication.getInstance().getHelper().getOldFavorite();
									if(OldFavoriteList != null && OldFavoriteList.size()>0){
										for(int i=0;i<OldFavoriteList.size();i++){
											Log.e("OldFavoriteList.get(i).getTitle()"+OldFavoriteList.get(i).getTitle());
											TVApplication.getInstance().getHelper().getWritableDatabase().execSQL("update onlineVideo SET isFavorite = 1 where title = '"+OldFavoriteList.get(i).getTitle()+"'");
										}
									}
									MaxSourceNum  =  OnlineVideoSourceDao.queryData("select * from OnlineVideoSource where SOURCENUM  = (select max(SOURCENUM) from OnlineVideoSource)").getSourcenum();
									Log.e("MaxSourceNum-->"+MaxSourceNum);
								} catch (SQLException e) {
									e.printStackTrace();
								}
								initPrograms = false;
								uiHandler.sendEmptyMessage(0);
							}
						}

					}.execute();
					// 没有节目数据时，保存好节目单后取第一个ID
					mFirstPath = root.get(0).getSourceList().get(0).getLink();
//					mFirstPath = OnlineVideoSourceDao.queryForId(1).getLink();
				} else {
					// 有节目数据时，获取最后观看的地址
					OnlineVideoSourcedata = OnlineVideoSourceDao.queryWhereEqData("isLastWatch", true, null, true);
					if(OnlineVideoSourcedata != null && !StringUtil.isEmpty(OnlineVideoSourcedata.getLink())){
						mFirstPath = OnlineVideoSourcedata.getLink();
					}else{
						// 没有节目数据时，保存好节目单后取第一个ID
						mFirstPath = OnlineVideoSourceDao.queryForId(1).getLink();
					}
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		
		setVolumeControlStream(AudioManager.STREAM_MUSIC);
		
		if(getIntent().getData() != null){
			isExternalVideo = true;
		}else{
			isExternalVideo = false;
		}
		parseIntent(getIntent());
		loadView(R.layout.activity_tv_videoview);
		manageReceivers();
		initProgramsList();
		fm = getSupportFragmentManager();
		
		settings = getSharedPreferences(PREFS_NAME, 0);
		String date = settings.getString("date", "0");
		SimpleDateFormat simpleDateParser = new SimpleDateFormat("yyyy-MM-dd");
		CuttentDate  = simpleDateParser.format(new Date());
		//测试用时间
		date = "2013-01-01";
		if(CuttentDate.compareTo(date)>0){
			downloadXml();
		}
		mCreated = true;
	}
    /**
     * 检查是否当前应用是否为最新版本
     */
    private void checkUpgradeApk() {      
      //第一步:初始化
    	final FlagUpdateManager flagUpdateManager = FlagUpdateManager.getInstance();
		flagUpdateManager.checkUpadatePackage(this, getResources().getString(R.string.APP_ID), getAppVersionName(this));
		//第二步:设置DownloadDialog显示的位置
		flagUpdateManager.showDownloadDialog(this);
		//第三步:设置UpdateDialog显示的位置
		flagUpdateManager.showUpdateDialog(this);

    }
    /**
	 * 返回当前程序版本号
	 */
	public static String getAppVersionName(Context context) {
		try {
			PackageManager pm = context.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
			return pi.versionName;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
	
	/**
	 * 复制文件到data
	 * @param InputStream
	 */
	private boolean copyFile(String assetsfile) {
		try {
			long a = System.currentTimeMillis();
			// 如果是文件
			InputStream is = getAssets().open(assetsfile);
			File file = new File(Environment.getDataDirectory() + "/data/" + getPackageName() + "/files/" + "online.xml");
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			OutputStream fos = new FileOutputStream(file);
			byte[] buffer = new byte[1024];
			int count = 0;
			while (true) {
				count++;
				int len = is.read(buffer);
				if (len == -1) {
					break;
				}
				fos.write(buffer, 0, len);
			}
			is.close();
			fos.close();
			Log.e("复制成功时间：" + (System.currentTimeMillis() - a));
			return true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 下载xml更新文件
	 */
	private void downloadXml() {
		try {
			String updatepath = path + updateurl.substring(updateurl.lastIndexOf("/"));
			final File file = new File(updatepath);
			if (file.exists()) {
				System.out.println("删除原文件下载更新");
				file.delete();
			}
			
		TransferListener transferListener = new TransferListener() {
			@Override
			public void handleProgress(String url, float progress) {
				// 设置下载进度
				Log.e( "progress-->" + progress);
			}

			@Override
			public void handleEvent(Event event) {
				switch (event.getTransferStatus()) {
				case Event.TRANSFER_STATUS_COMPLETED:
					// 下载完成
					Log.e("更新文件下载完成");
					unzipxml();

					break;
				case Event.TRANSFER_STATUS_PAUSED:
					// 已暂停

					break;
				case Event.TRANSFER_STATUS_FAILED:
					// 传输失败
					System.out.println("传输失败");
					break;
				case Event.TRANSFER_STATUS_UNKNOW:
					// 未知错误
					System.out.println("未知错误");
					break;
				default:
					break;
				}
			}
		};

		
			DownloadManager.createDownloadTask(updateurl, 3, updatepath, transferListener);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 解析xml
	 * 
	 * @param transferListener
	 */
	private void unzipxml() {

		String updatepath = path + updateurl.substring(updateurl.lastIndexOf("/"));
		final File file = new File(updatepath);
		try {
			final Online o = XmlReaderHelper.getOnlineTVUpdateFile(new FileInputStream(file));
			System.out.println("name-->" + o.getName());
			System.out.println("url-->" + o.getUrl());
			System.out.println("version-->" + o.getVersion());

			String version = settings.getString("version", "0");
			if (o.getVersion().compareTo(version) > 0) {
				final File dirpathfile = new File(dirpath);
				if (dirpathfile.exists()) {
					dirpathfile.delete();
				}

				TransferListener transferListener = new TransferListener() {
					@Override
					public void handleProgress(String url, float progress) {
						// 设置下载进度
						Log.e("progress-->" + progress);
					}

					@Override
					public void handleEvent(Event event) {
						switch (event.getTransferStatus()) {
						case Event.TRANSFER_STATUS_COMPLETED:
							// 下载完成
							Log.e("xml下载完成");
							// 写入配置文件。可以使用SharedPreferences.Editor来辅助解决。
							SharedPreferences.Editor editor = settings.edit();
							editor.putString("version", o.getVersion());
							editor.putString("date", CuttentDate);
							editor.commit(); // 一定要记得提交
							if(file.exists()){
								System.out.println("删除升级包");
								file.delete();
							}
							break;
						case Event.TRANSFER_STATUS_PAUSED:
							// 已暂停
							if (dirpathfile.exists()) {
								dirpathfile.delete();
							}
							break;
						case Event.TRANSFER_STATUS_FAILED:
							// 传输失败
							System.out.println("传输失败");
							if (dirpathfile.exists()) {
								dirpathfile.delete();
							}
							break;
						case Event.TRANSFER_STATUS_UNKNOW:
							// 未知错误
							System.out.println("未知错误");
							if (dirpathfile.exists()) {
								dirpathfile.delete();
							}
							break;
						default:
							break;
						}
					}
				};

				DownloadManager.createDownloadTask(o.getUrl(), 3, dirpath, transferListener);
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private class UIHandler extends Handler {
		private WeakReference<Context> mContext;

		public UIHandler(Context c) {
			mContext = new WeakReference<Context>(c);
		}

		public void handleMessage(Message msg) {
			VideoActivity ctx = (VideoActivity) mContext.get();
			switch (msg.what) {
			case 0:
				initTVFragment();
				break;
			}
		}
	};
	
	private void initProgramsList() {
		mMenuWidth = (int) getResources().getDimension(R.dimen.tv_programs_list_width);
		mMenuHeight = (int) getResources().getDimension(R.dimen.tv_programs_list_height);

		mTvPrograms = (RelativeLayout) findViewById(R.id.tv_programs);
		mTvProgramsTextView = (TextView)findViewById(R.id.tv_programs_textview);
		mTvProgramsGridview = (GridView) findViewById(R.id.tv_programs_gridview);

		mTabList = (SyncHorizontalScrollView) findViewById(R.id.tab_list);
		mTabScroll = (RelativeLayout) findViewById(R.id.tab_scroll);
		mTabContent = (RadioGroup) findViewById(R.id.tab_content);
		mTabTVPager = (ViewPager) findViewById(R.id.vPager);
		mTabTVPager.removeAllViews();
		// mTabLeft = (ImageView) findViewById(R.id.main_iv_left);
		// mTabRight = (ImageView) findViewById(R.id.main_iv_right);
		mTabList.setSomeParam(mTabScroll, null, null, VideoActivity.this);
		initTabContent();
		initTabValue();
		setListener();
		
	}

	public void initTVFragment() {
		try {
			Log.e("initTVFragment()");
			mMenuDrawer.setTouchMode(MenuDrawer.TOUCH_MODE_FULLSCREEN);
			OnlineVideoSource CurrentOnlineVideoSource = getCurrentOnlineVideoSource(mFirstPath);
			if(CurrentOnlineVideoSource != null){
				Log.e("CurrentOnlineVideoSource");
				String mCurrentSourcenum = CurrentOnlineVideoSource.getSourcenum();
				if(!StringUtil.isEmpty(mCurrentSourcenum)){
//					mCurrentID = onlineDao.queryData("SELECT * FROM ONLINEVIDEO WHERE num = '" + mCurrentSourcenum + "' limit 0,1").id;
					QueryBuilder<OnlineVideo, Integer> preparedQuery = onlineDao.queryBuilder();
					preparedQuery.where().eq("num", mCurrentSourcenum);
					OnlineVideo mCurrentOnlineVideo =  onlineDao.queryForFirst(preparedQuery.prepare());
					if(mCurrentOnlineVideo != null){
						mCurrentID = mCurrentOnlineVideo.id;
					}
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		if (mTabTVPagerAdapter == null) {
			Log.e("mTabTVPagerAdapter :::"+mTabTitle.length);
			mTabTVPagerAdapter = new TVFragmentPagerAdapter(fm, mTabTitle,mCurrentID);
			mTabTVPager.setAdapter(mTabTVPagerAdapter);
		} else {
			Log.e("mTabTVPagerAdapter====>notifyDataSetChanged");
			mTabTVPagerAdapter.notifyDataSetChanged();
		}
		mTabTVPager.setCurrentItem(0);
	}

	private OnlineVideoSource getCurrentOnlineVideoSource(String path) {
//		String mCurrentSourcenum = OnlineVideoSourceDao.queryData("SELECT * FROM ONLINEVIDEOSOURCE WHERE link = '" + mUri.toString() + "' limit 0,1").getSourcenum();
		try {
			QueryBuilder<OnlineVideoSource,Integer> preparedQuery = OnlineVideoSourceDao.queryBuilder();
			preparedQuery.where().eq("link", path);
			OnlineVideoSource mNextOnlineVideoSource =  OnlineVideoSourceDao.queryForFirst(preparedQuery.prepare());
			return mNextOnlineVideoSource;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	private String getCurrentOnlineVideoTitle(String path) {
		try {
			OnlineVideoSource CurrentOnlineVideoSource = getCurrentOnlineVideoSource(path);
			if (CurrentOnlineVideoSource == null)
				return "";
			String mCurrentSourcenum = CurrentOnlineVideoSource.getSourcenum();
			if (!StringUtil.isEmpty(mCurrentSourcenum)) {
				
				QueryBuilder<OnlineVideo, Integer> preparedQuery = onlineDao.queryBuilder();
				preparedQuery.where().eq("num", mCurrentSourcenum);
				OnlineVideo mOnlineVideo =  onlineDao.queryForFirst(preparedQuery.prepare());
				
//				OnlineVideo  mOnlineVideo =  onlineDao.queryData("SELECT * FROM ONLINEVIDEO WHERE num = '" + mCurrentSourcenum + "' limit 0,1");
				if(mOnlineVideo != null){
					mCurrentTitle = "频道" + mOnlineVideo.id + "  " +mOnlineVideo.title;
				}
			}
			return mCurrentTitle;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return "";

	}
	
	/**
	 * 设置默认地址源
	 * @param path
	 */
	private boolean setDefaultLink(String path) {
		try {
			OnlineVideoSource CurrentOnlineVideoSource = getCurrentOnlineVideoSource(path);
			if (CurrentOnlineVideoSource == null)
				return false;
			String mCurrentSourcenum = CurrentOnlineVideoSource.getSourcenum();
			if (!StringUtil.isEmpty(mCurrentSourcenum)) {
				OnlineVideoSourceDao.updateRaw("update OnlineVideoSource set defaultLink = '0' where sourcenum = '"+mCurrentSourcenum+"'");
				OnlineVideoSourceDao.updateRaw("update OnlineVideoSource set defaultLink = '1' where link = '"+path+"'");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return true;
	}
	
	private void initTabContent() {
		for (int i = 0; i < mTabTitle.length; i++) {
			RadioButton radioButton = (RadioButton) LayoutInflater.from(VideoActivity.this).inflate(R.layout.activity_tv_programs_item, null);
			radioButton.setOnFocusChangeListener(new View.OnFocusChangeListener() {

				@Override
				public void onFocusChange(View v, boolean hasFocus) {
					if (hasFocus) {
						v.performClick();
					}

				}
			});
			radioButton.setId(i);
			radioButton.setText(mTabTitle[i]);
			radioButton.setLayoutParams(new LayoutParams(mMenuWidth / mTabTitle.length, LayoutParams.FILL_PARENT));
			mTabPages.add(radioButton);

		}

	}

	private void initTabValue() {
		mTabContent.removeAllViews();
		for (int i = 0; i < mTabTitle.length; i++) {
			mTabPages.get(i).setText(mTabTitle[i]);
			mTabContent.addView(mTabPages.get(i));
		}
		mTabContent.check(0);
	}

	private void setListener() {
		mTabContent.setOnCheckedChangeListener(mTabonCheckedChangeListener);
		mTabTVPager.setOnPageChangeListener(new mTabOnPageChangeListener());

	}

	// 页卡切换监听
	public class mTabOnPageChangeListener implements OnPageChangeListener {

		@Override
		public void onPageSelected(int position) {
			if (mTabPages != null && mTabPages.size() > position) {
				((RadioButton) mTabPages.get(position)).performClick();
			}
			
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
			
		}

	}

	// RadioGroup点击CheckedChanged监听
	private OnCheckedChangeListener mTabonCheckedChangeListener = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId) {
			try {
				if (mTabContent != null && mTabContent.getChildCount() > 0 && mTabContent.getChildAt(checkedId) != null) {
					// TranslateAnimation _TranslateAnimation = new
					// TranslateAnimation(
					// mCurrentCheckedRadioLeft,
					// ((RadioButton) tab_content.getChildAt(checkedId))
					// .getLeft(), 0f, 0f);
					// _TranslateAnimation
					// .setInterpolator(new LinearInterpolator());
					// _TranslateAnimation.setDuration(100);
					// _TranslateAnimation.setFillAfter(true);
					// cursor.startAnimation(_TranslateAnimation);
					mTabTVPager.setCurrentItem(checkedId);// 让下方ViewPager跟随上面的HorizontalScrollView切换
					// mCurrentCheckedRadioLeft = ((RadioButton) mTabContent
					// .getChildAt(checkedId)).getLeft();
					if(mTabContent.getChildCount() > 2){
						mTabList.smoothScrollTo((checkedId > 1 ? ((RadioButton) mTabContent.getChildAt(checkedId)).getLeft() : 0) - ((RadioButton) mTabContent.getChildAt(2)).getLeft(), 0);
					}
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	};

	private boolean isExternalVideo;

	private String mChangeLink = "";

	private int mMaxVolume;

	private AudioManager mAM;

	private int mCurrentTVLinkIndex;

	private String MaxSourceNum = "0";

	private void attachMediaController() {
		if (mMediaController != null) {
			mNeedLock = mMediaController.isLocked();
			mMediaController.release();
		}
		mMediaController = new MediaController(this, mNeedLock);
		mMediaController.setMediaPlayer(this);
		if(isExternalVideo){
			mMediaController.setAnchorView(mVideoView.getRootView());
		}
		setFileName();
		setBatteryLevel();
	}
	private void deattachMediaController() {
		if (mMediaController != null) {
			mNeedLock = mMediaController.isLocked();
			mMediaController.release();
		}
	}

	private void setVolume(int v) {
		if (v > mMaxVolume)
			v = mMaxVolume;
		else if (v < 0)
			v = 0;
		mAM.setStreamVolume(AudioManager.STREAM_MUSIC, v, 0);
//		NDToast.makeText(this, R.drawable.video_volumn_bg, "v-->"+v, 10).show();
		//NDToast.makeProgressText(this, (float) v / mMaxVolume, 10).show();
	}
	/**
	 * 切换源地址标记，
	 * false ： 地址源增加向上
	 * true	：地址源增加向下
	 */
	boolean UpDownflag;
	@Override
	public boolean dispatchKeyEvent(KeyEvent event)
	{
		Log.e("dispatchKeyEvent-->"+event.getKeyCode());
		switch (event.getKeyCode()) {
		case KeyEvent.KEYCODE_DPAD_RIGHT:
			
			if (!isOpenProgramsList() && mMediaController != null && event.getAction() != KeyEvent.ACTION_UP) {
				Log.e("dispatchKeyEvent--> KEYCODE_DPAD_RIGHT");
				mMediaController.toggleVideoMode(true, true);
				mVideoMode = mMediaController.mVideoMode;
				return true; // 这些标记为处理过，则不在往内部传递
			}
			break;
		case KeyEvent.KEYCODE_DPAD_LEFT:
			if (!isOpenProgramsList()  && event.getAction() != KeyEvent.ACTION_UP) {
				if(TVLinkList.size() == 1){
					return true;
				}
				if(mCurrentTVLinkIndex <= 0){
					UpDownflag = false;
				}
				if(mCurrentTVLinkIndex >=0 && mCurrentTVLinkIndex < TVLinkList.size() - 1 ){
					 if(!UpDownflag){
						 mCurrentTVLinkIndex++ ;
					 }else{
						 mCurrentTVLinkIndex-- ;
					 }
					 Log.e("mCurrentTVLinkIndex:::"+mCurrentTVLinkIndex);
					 Log.e("TVLinkList.size():::"+TVLinkList.size());
					 mUri = Uri.parse(TVLinkList.get(mCurrentTVLinkIndex));
					 Log.e("1："+mUri.toString());
					 vPlayerHandler.removeMessages(OPEN);
					 vPlayerHandler.sendEmptyMessageDelayed(OPEN, 1000);
					 
					 NDToast.makeText(this, "正在切换电视节目源："+(mCurrentTVLinkIndex+1) +"/"+TVLinkList.size(), 1000).show();
					 return true; // 这些标记为处理过，则不在往内部传递

				 }else if(mCurrentTVLinkIndex == TVLinkList.size() - 1){
					 UpDownflag = true;
					 mCurrentTVLinkIndex-- ;
					 if(mCurrentTVLinkIndex != -1){
						 mUri = Uri.parse(TVLinkList.get(mCurrentTVLinkIndex));
						 Log.e("2："+mUri.toString());
						 vPlayerHandler.removeMessages(OPEN);
						 vPlayerHandler.sendEmptyMessageDelayed(OPEN, 1000);
						 
						 NDToast.makeText(this, "正在切换电视节目源："+(mCurrentTVLinkIndex+1) +"/"+TVLinkList.size(), 1000).show();
					 }
					 return true; // 这些标记为处理过，则不在往内部传递

				 }
				 return true; // 这些标记为处理过，则不在往内部传递
			}
			break;
		case KeyEvent.KEYCODE_ENTER:
			Log.e("dispatchKeyEvent keyCode-->  KeyEvent.KEYCODE_ENTER");
			if(!isOpenProgramsList()){
				showORhideProgramsList();
				mTabTVPager.setCurrentItem(0);
				return true; // 这些标记为处理过，则不在往内部传递
			}
			break;
		
//		case KeyEvent.KEYCODE_VOLUME_UP: // 音量键+
//		case KeyEvent.KEYCODE_VOLUME_DOWN: // 音量键-
//		case KeyEvent.KEYCODE_CAMERA: // 拍照键
//		case KeyEvent.KEYCODE_HOME: // 拍HOME键
//			return true; // 这些标记为处理过，则不在往内部传递
		default:
			break;
	    }
	    return super.dispatchKeyEvent(event);
	}
	
	
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		Log.e("onKeyUp keyCode-->" + keyCode);
		switch (keyCode) {
//		case KeyEvent.KEYCODE_ENTER:
//			Log.e("onKeyUp keyCode-->" + KeyEvent.KEYCODE_ENTER);
//			showORhideProgramsList();
//			mTabTVPager.setCurrentItem(0);
//			if(!isOpenProgramsList() && mMediaController != null){
//				mMediaController.toggleVideoMode(true, true);
//				return false;
//			}
//			break;
//		case KeyEvent.KEYCODE_VOLUME_UP:
//		case KeyEvent.KEYCODE_VOLUME_DOWN:
//			mAM = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
//			mMaxVolume = mAM.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
//			int mVolume = mAM.getStreamVolume(AudioManager.STREAM_MUSIC);
//			int step = keyCode == KeyEvent.KEYCODE_VOLUME_UP ? 1 : -1;
//			setVolume(mVolume + step);
//			break;
//		case KeyEvent.KEYCODE_DPAD_RIGHT:
//			if(!isOpenProgramsList() && mMediaController != null){
//				mMediaController.toggleVideoMode(true, true);
//				mVideoMode = mMediaController.mVideoMode;
//				return true;
//			}
//			break;
		case KeyEvent.KEYCODE_DPAD_UP:
			UpDownflag = false;
			if(initPrograms){
				NDToast.makeText(VideoActivity.this, R.string.vitamio_init_db, 1000).show();
				
			}else if(!isOpenProgramsList()){
				Message message = vPlayerHandler.obtainMessage(OPEN_NEXT);
				message.obj = -1;
				vPlayerHandler.removeMessages(OPEN_NEXT);
				vPlayerHandler.sendMessageDelayed(message, 1000);
				
			}
			break;

		case KeyEvent.KEYCODE_DPAD_DOWN:
			UpDownflag = false;
			if(initPrograms){
				NDToast.makeText(VideoActivity.this, R.string.vitamio_init_db, 1000).show();

			}else if(!isOpenProgramsList()){
				Message message = vPlayerHandler.obtainMessage(OPEN_NEXT);
				message.obj = 1;
				vPlayerHandler.removeMessages(OPEN_NEXT);
				vPlayerHandler.sendMessageDelayed(message, 1000);
				
			}
			break;
		case KeyEvent.KEYCODE_BACK:
			//键盘
			if(isOpenProgramsList()){
				hideProgramsList();
			}else{
//				if(!initPrograms && isInitialized()){
//					Log.e("完全退出");
//					finish();
//					release();
//				}
				
				//平板上退出需要加这段代码
				if(initPrograms){
					NDToast.makeText(VideoActivity.this, R.string.vitamio_init_db, 1000).show();
				}else{
					finish();
				}
			}
			//触摸
//			showORhideProgramsList();
//			mTabTVPager.setCurrentItem(0);
			break;
		default:
			break;
		}
//		return super.onKeyUp(keyCode, event);
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
//		Log.e("鼠标点击："+ev.getAction());
//		Log.e("鼠标点击ev.getSource():"+ev.getSource());
//		Log.e("鼠标点击ev.getPointerCount():"+ev.getPointerCount());//获取点击事件的数量
//		Log.e("鼠标点击ev.getToolType(0)=MotionEvent.TOOL_TYPE_MOUSE:"+ev.getToolType(0));
		if(ev.getSource() == 8194){
			//SOURCE_MOUSE	8194（0x00002002）鼠标
			if(ev.getAction() == MotionEvent.ACTION_UP){
				if(!isOpenProgramsList()){
					showORhideProgramsList();
					mTabTVPager.setCurrentItem(0);
				}
			}
		}
		return super.dispatchTouchEvent(ev);
	}
	/**
	 * 上下键切换电视节目
	 * @param id （1，or -1）代表下(上)个节目
	 */
	private void changeTVProgramsByKey(String num) {
		try {
			Log.e("Integer.parseInt(num)-->"+Integer.parseInt(num));
			
			String mCurrentSourcenum = OnlineVideoSourceDao.queryData("SELECT * FROM ONLINEVIDEOSOURCE WHERE link = '" + mUri.toString() + "' limit 0,1").getSourcenum();
			mChangeLink  = changeTVProgram(mCurrentSourcenum,Integer.parseInt(num));
			if(!StringUtil.isEmpty(mChangeLink)){
				mUri = Uri.parse(mChangeLink);
				new VPlayerInitialTask().execute(new Boolean[0]);
				
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 切换频道
	 * @param mCurrentSourcenum 源的sourcenum
	 * @param num 增加或减少频道num
	 * @return
	 */
	private String changeTVProgram(String mCurrentSourcenum,int num) {
		String mNextLink = null;
		try {
			int mNextNum = Integer.parseInt(mCurrentSourcenum) + num;
			if(mNextNum > 0 && mNextNum <= Integer.parseInt(MaxSourceNum) ){
				String mNextSourcenum = String.valueOf(mNextNum);
				if(mNextSourcenum.length() == 1){
					mNextSourcenum = "00" + mNextSourcenum;
				}else if(mNextSourcenum.length() == 2){
					mNextSourcenum = "0" + mNextSourcenum;
				}
				Log.e("mCurrentSourcenum-->"+mCurrentSourcenum+";mNextSourcenum-->"+mNextSourcenum);
				QueryBuilder<OnlineVideoSource,Integer> preparedQuery = OnlineVideoSourceDao.queryBuilder();
				preparedQuery.where().eq("sourcenum", mNextSourcenum);
				List<OnlineVideoSource> OnlineVideoSourceList = OnlineVideoSourceDao.query(preparedQuery.prepare());
				
				if (OnlineVideoSourceList != null && OnlineVideoSourceList.size() > 0) {
					TVLinkList.clear();
					for (int i = 0; i < OnlineVideoSourceList.size(); i++) {
						TVLinkList.add(OnlineVideoSourceList.get(i).getLink());
						Log.e("地址:" + TVLinkList.get(i));
					}
					
					QueryBuilder<OnlineVideoSource,Integer> defaultPreparedQuery = OnlineVideoSourceDao.queryBuilder();
					defaultPreparedQuery.where().eq("sourcenum", mNextSourcenum).and().eq("defaultLink", true);
					OnlineVideoSource  OnlineVideoSource= OnlineVideoSourceDao.queryForFirst(defaultPreparedQuery.prepare());
//					OnlineVideoSource OnlineVideoSource = OnlineVideoSourceDao.queryData("SELECT * FROM ONLINEVIDEOSOURCE WHERE sourcenum = '"+mNextSourcenum+"' AND defaultLink = '1'");

					if(OnlineVideoSource != null){
						Log.e("测试消息 ，此电视源为默认源");
						mNextLink = OnlineVideoSource.getLink();
						mCurrentTVLinkIndex = 0;
						for(int i=0;i< TVLinkList.size();i++){
							if(TVLinkList.get(i).equals(mNextLink)){
								mCurrentTVLinkIndex = i;
							}
						}
					}else{
						Log.e("测试消息 ，此电视源不是默认源");
						mCurrentTVLinkIndex = 0;
						mNextLink = TVLinkList.get(0);
					}
					
				} else {
					mNextLink = changeTVProgram(mNextSourcenum, num);
				}
//				if(mNextOnlineVideoSource == null){
//					mNextLink = changeTVProgram(mNextSourcenum, num);
//				}else{
//					mNextLink =	mNextOnlineVideoSource.getLink();
//				}
			}
			return mNextLink;
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	
	@Override
	public void onStart() {
		super.onStart();
		Log.e("VideoActivity onStart");
		if (!mCreated)
			return;
		Intent serviceIntent = new Intent(this, PlayerService.class);
		serviceIntent.putExtra("isHWCodec", mIsHWCodec);
		bindService(serviceIntent, vPlayerServiceConnection, Context.BIND_AUTO_CREATE);
		
	}

	@Override
	public void onResume() {
		super.onResume();
		Log.e("VideoActivity onResume");
		
		if (!mCreated)
			return;
		
		MobclickAgent.onResume(this);
		if(!initPrograms){
			Log.e("VideoActivity initPrograms");
			initTVFragment();
		}
		if (isInitialized()) {
			KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
			if (!keyguardManager.inKeyguardRestrictedInputMode()) {
				startPlayer();
			}
		} else {
			if (mCloseComplete) {
				reOpen();
			}
		}
		try {
			if(!initPrograms){
//				QueryBuilder<OnlineVideoSource,Integer> preparedQuery = OnlineVideoSourceDao.queryBuilder();
//				preparedQuery.where().eq("sourcenum", mNextSourcenum);
//				List<OnlineVideoSource> OnlineVideoSourceList = OnlineVideoSourceDao.query(preparedQuery.prepare());
				
				
				OnlineVideoSource mMaxOnlineVideoSource = OnlineVideoSourceDao.queryData("select * from OnlineVideoSource where SOURCENUM  = (select max(SOURCENUM) from OnlineVideoSource)");
				if(mMaxOnlineVideoSource != null){
					MaxSourceNum  =  mMaxOnlineVideoSource.getSourcenum();
					Log.e("MaxSourceNum-->"+MaxSourceNum);
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onPause() {
		super.onPause();
		Log.e("onPause");
		if (!mCreated)
			return;
		MobclickAgent.onPause(this);
		if (isInitialized()) {
			// savePosition();
			if (vPlayer != null && vPlayer.isPlaying()) {
				stopPlayer();
			}
		}
	}

	@Override
	public void onStop() {
		super.onStop();
		Log.e("VideoActivity onStop");
		if (!mCreated)
			return;
		if (isInitialized()) {
			vPlayer.releaseSurface();
		}
		if (mServiceConnected) {
			unbindService(vPlayerServiceConnection);
			mServiceConnected = false;
		}

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.e("VideoActivity onDestroy");
		//添加静默安装更新
		FlagUpdateManager.getInstance().startSilentInstall(this);
		if (!mCreated)
			return;
		manageReceivers();
		if (isInitialized() && !vPlayer.isPlaying())
			// 完全关闭
			// release();
			if (mMediaController != null)
				mMediaController.release();
		
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		if (isInitialized()) {
			setVideoLayout();
//			attachMediaController();
		}

		super.onConfigurationChanged(newConfig);
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();

	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// http://code.google.com/p/android/issues/detail?id=19917
		outState.putString("WORKAROUND_FOR_BUG_19917_KEY", "WORKAROUND_FOR_BUG_19917_VALUE");
		super.onSaveInstanceState(outState);
	}

	public void showMenu() {
		  	
	}

	private void loadView(int id) {
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		ScreenWidth = dm.widthPixels;
		ScreenHeight = dm.heightPixels;
		Log.e("ScreenWidth-->" + ScreenWidth + ";ScreenHeight-->" + ScreenHeight);
		mMenuDrawer = MenuDrawer.attach(this, MenuDrawer.MENU_DRAG_CONTENT);
		mMenuDrawer.setContentView(id);
		mMenuDrawer.setMenuView(R.layout.activtiy_tv_programs_list);
		mMenuDrawer.setTouchMode(MenuDrawer.TOUCH_MODE_NONE);
		mMenuDrawer.setOnDrawerStateChangeListener(new OnDrawerStateChangeListener() {

			@Override
			public void onDrawerStateChange(int oldState, int newState) {
				
				if (newState == MenuDrawer.STATE_OPEN) {
					Log.e("MenuDrawer.STATE_OPEN");
					//设置节目列表
					RelativeLayout.LayoutParams ProgramsListParams = (RelativeLayout.LayoutParams) mTvPrograms.getLayoutParams();
					if (ProgramsListParams.width != mMenuWidth) {
						ProgramsListParams.height = (int) getResources().getDimension(R.dimen.tv_programs_list_height);
						ProgramsListParams.width = (int) (ScreenWidth - getResources().getDimension(R.dimen.tv_programs_list_width));

						mTvPrograms.setLayoutParams(ProgramsListParams);
					}
					// 显示节目列表
					mTvPrograms.setVisibility(View.VISIBLE);
					// 设置窗口大小
					RelativeLayout.LayoutParams Params = (RelativeLayout.LayoutParams) mViewRoot.getLayoutParams();
					Params.height = (int) (/* ScreenHeight */DeviceUtils.getScreenHeight(VideoActivity.this) - getResources().getDimension(R.dimen.tv_programs_list_height));
					Params.width = (int) (/* ScreenWidth */DeviceUtils.getScreenWidth(VideoActivity.this) - getResources().getDimension(R.dimen.tv_programs_list_width));

					mViewRoot.setLayoutParams(Params);

					float windowRatio = Params.width / (float) Params.height;
					// 设置视频画面大小
					if(mCreated && vPlayer != null){
						int videoWidth = vPlayer.getVideoWidth();
						int videoHeight = vPlayer.getVideoHeight();
						float videoRatio = vPlayer.getVideoAspectRatio();
						LayoutParams lp = mVideoView.getLayoutParams();
	
						Log.e("windowRatio-->" + windowRatio + ",videoRatio-->" + videoRatio);
						lp.width = ((windowRatio < videoRatio) ? (int) (Params.width * 0.9) : (int) (Params.height * windowRatio * 0.9));
						lp.height = (windowRatio > videoRatio) ? (int) (Params.height * 0.9) : (int) (Params.width / videoRatio * 0.9);
						// Log.e("videoWidth-->"+videoWidth+",videoHeight-->"+videoHeight+",videoRatio-->"+videoRatio);
						// Log.e("lp.width-->"+lp.width+",lp.height-->"+lp.height);
						
						mVideoView.setLayoutParams(lp);
					}
				}
				if (newState == MenuDrawer.STATE_CLOSED || newState == MenuDrawer.STATE_CLOSING) {
					// 隐藏节目详细列表
					mTvPrograms.setVisibility(View.GONE);
					// 设置窗口大小
					RelativeLayout.LayoutParams Params = (RelativeLayout.LayoutParams) mViewRoot.getLayoutParams();
					if (Params.width != ScreenWidth) {
						Params.height = ScreenHeight;
						Params.width = ScreenWidth;
						mViewRoot.setLayoutParams(Params);
					}

					// 设置视频画面大小
//					setFullVideoLayout();
					setVideoLayout();
				}

			}
		});
		
		// setContentView(id);
		mViewRoot = findViewById(R.id.video_root);
		mVideoView = (VideoView) findViewById(R.id.video);
		mVideoView.initialize(this, this, mIsHWCodec);
		mSubtitleContainer = findViewById(R.id.subtitle_container);
		mSubtitleText = (OutlineTextView) findViewById(R.id.subtitle_text);
		mSubtitleImage = (ImageView) findViewById(R.id.subtitle_image);
		mVideoLoadingText = (TextView) findViewById(R.id.video_loading_text);
		mVideoLoadingLayout = findViewById(R.id.video_loading);
		mLoadingProgressView = mVideoLoadingLayout.findViewById(R.id.video_loading_progress);

		mLoadingAnimation = AnimationUtils.loadAnimation(VideoActivity.this, R.anim.loading_rotate);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
	}

	private void parseIntent(Intent i) {
			Uri dat = /* IntentHelper.getIntentUri(i) */i.getData();
			if (dat == null){
				if (mFirstPath != null) {
					dat = Uri.parse(mFirstPath);
				} else {
					dat = Uri.parse(defaultpath);
				}
					
			}
			// resultFinish(RESULT_FAILED);

			String datString = dat.toString();
			if (!datString.equals(dat.toString()))
				dat = Uri.parse(datString);

			mUri = dat;

		

		mNeedLock = i.getBooleanExtra("lockScreen", false);
		mDisplayName = i.getStringExtra("displayName");
		mFromStart = i.getBooleanExtra("fromStart", false);
		mSaveUri = i.getBooleanExtra("saveUri", true);
		mStartPos = i.getFloatExtra("startPosition", -1.0f);
		mLoopCount = i.getIntExtra("loopCount", 1);
		mParentId = i.getIntExtra("parentId", 0);
		mSubPath = i.getStringExtra("subPath");
		mSubShown = i.getBooleanExtra("subShown", true);
		mIsHWCodec = i.getBooleanExtra("hwCodec", false);
		Log.i("L: %b, N: %s, S: %b, P: %f, LP: %d", mNeedLock, mDisplayName, mFromStart, mStartPos, mLoopCount);
	}

	private void manageReceivers() {
		if (!mReceiverRegistered) {
			mScreenReceiver = new ScreenReceiver();
			registerReceiver(mScreenReceiver, SCREEN_FILTER);
			mUserPresentReceiver = new UserPresentReceiver();
			registerReceiver(mUserPresentReceiver, USER_PRESENT_FILTER);
			mBatteryReceiver = new BatteryReceiver();
			registerReceiver(mBatteryReceiver, BATTERY_FILTER);
			mHeadsetPlugReceiver = new HeadsetPlugReceiver();
			registerReceiver(mHeadsetPlugReceiver, HEADSET_FILTER);
			mReceiverRegistered = true;
			
			startNetworkListener();
			//注册网络状态监听器
			IntentFilter filter = new IntentFilter();    
			filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);   
			registerReceiver(NetworkStateReceiver, filter); 
	        
		} else {
			try {
				//注销网络监听
				unregisterReceiver(NetworkStateReceiver);
				
				if (mScreenReceiver != null)
					unregisterReceiver(mScreenReceiver);
				if (mUserPresentReceiver != null)
					unregisterReceiver(mUserPresentReceiver);
				if (mHeadsetPlugReceiver != null)
					unregisterReceiver(mHeadsetPlugReceiver);
				if (mBatteryReceiver != null)
					unregisterReceiver(mBatteryReceiver);
			} catch (IllegalArgumentException e) {
			}
			mReceiverRegistered = false;
		}
	}

	private void setFileName() {
		if (mUri != null) {
			String name = null;
			if (mUri.getScheme() == null || mUri.getScheme().equals("file"))
				name = FileUtils.getName(mUri.toString());
			else
				name = mUri.getLastPathSegment();
			if (name == null)
				name = "null";
			if (mDisplayName == null)
				mDisplayName = name;
			mMediaController.setFileName(mDisplayName);
		}
	}

	private void applyResult(int resultCode) {
		vPlayerHandler.removeMessages(BUFFER_PROGRESS);
//		Intent i = new Intent();
//		i.putExtra("filePath", mUri.toString());
//		if (isInitialized()) {
//			i.putExtra("position", (double) vPlayer.getCurrentPosition() / vPlayer.getDuration());
//			i.putExtra("duration", vPlayer.getDuration());
//			 savePosition();
//		}
		switch (resultCode) {
		case RESULT_FAILED:
//			ToastHelper.showToast(this, Toast.LENGTH_LONG, R.string.closing_file);
			break;
		case RESULT_CANCELED:
		case RESULT_OK:
			break;
		}
//		setResult(resultCode, i);
	}

	private void resultFinish(int resultCode) {
		applyResult(resultCode);
		//打开失败后不直接退出,reopen
//		reOpen();
//		if (UIUtils.hasICS() && resultCode != RESULT_FAILED) {
//			android.os.Process.killProcess(android.os.Process.myPid());
//		} else {
//			finish();
//		}
	}

	private void release() {
		if (vPlayer != null) {
			if (UIUtils.hasICS()) {
				android.os.Process.killProcess(android.os.Process.myPid());
			} else {
				vPlayer.release();
				vPlayer.releaseContext();
			}
		}
	}

	private void reOpen(Uri path, String name, boolean fromStart) {
		if (isInitialized()) {
			// savePosition();
			vPlayer.release();
			vPlayer.releaseContext();
		}
		Intent i = getIntent();
		if (mMediaController != null) {
			i.putExtra("lockScreen", mMediaController.isLocked());
		}
		i.putExtra("startPosition", (float) mSession.getDouble(mUri + VP.SESSION_LAST_POSITION_SUFIX, 7.7f));
		i.putExtra("fromStart", fromStart);
		i.putExtra("displayName", name);
		i.setData(path);
		parseIntent(i);
		mUri = path;
		if (mViewRoot != null)
			mViewRoot.invalidate();
		mOpened.set(false);
	}

	public void reOpen() {
		reOpen(mUri, mDisplayName, false);
	}

	protected void startPlayer() {
		if (isInitialized() && mScreenReceiver.screenOn && !vPlayer.isBuffering()) {
			Log.i("VideoActivity#startPlayer");
			if (!vPlayer.isPlaying()) {
				vPlayer.start();
				if (UIUtils.hasHoneycomb()) {
					getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LOW_PROFILE);
				}
				
				try {
					OnlineVideoSourceDao.updateRaw("update OnlineVideoSource set isLastWatch = '0' ");
					OnlineVideoSourceDao.updateRaw("update OnlineVideoSource set isLastWatch = '1' where link = '"+mUri.toString()+"'");
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		
	}

	protected void stopPlayer() {
		if (isInitialized()) {
			vPlayer.stop();
		}
	}

	private void setBatteryLevel() {
		if (mMediaController != null)
			mMediaController.setBatteryLevel(mBatteryLevel);
	}

	private class BatteryReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
			int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
			int percent = scale > 0 ? level * 100 / scale : 0;
			if (percent > 100)
				percent = 100;
			mBatteryLevel = String.valueOf(percent) + "%";
			setBatteryLevel();
		}
	}

	private class UserPresentReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (isRootActivity()) {
				startPlayer();
			}
		}
	}

	private boolean isRootActivity() {
		ActivityManager activity = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
		return activity.getRunningTasks(1).get(0).topActivity.flattenToString().endsWith("io.vov.vitamio.activity.VideoActivity");
	}

	public class HeadsetPlugReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent != null && intent.hasExtra("state")) {
				int state = intent.getIntExtra("state", -1);
				if (state == 0) {
					mHeadsetPlaying = isPlaying();
					stopPlayer();
				} else if (state == 1) {
					if (mHeadsetPlaying)
						startPlayer();
				}
			}
		};
	}

	private class ScreenReceiver extends BroadcastReceiver {
		private boolean screenOn = true;

		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
				screenOn = false;
				stopPlayer();
			} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
				screenOn = true;
			}
		}
	}

	private void loadVPlayerPrefs() {
		if (!isInitialized())
			return;
		vPlayer.setBuffer(VP.DEFAULT_BUF_SIZE);
		vPlayer.setVideoQuality(VP.DEFAULT_VIDEO_QUALITY);
		vPlayer.setDeinterlace(VP.DEFAULT_DEINTERLACE);
		vPlayer.setVolume(VP.DEFAULT_STEREO_VOLUME, VP.DEFAULT_STEREO_VOLUME);
		vPlayer.setSubEncoding(VP.DEFAULT_SUB_ENCODING);
		MarginLayoutParams lp = (MarginLayoutParams) mSubtitleContainer.getLayoutParams();
		lp.bottomMargin = (int) VP.DEFAULT_SUB_POS;
		mSubtitleContainer.setLayoutParams(lp);
		vPlayer.setSubShown(mSubShown);
		setTextViewStyle(mSubtitleText);
		if (!TextUtils.isEmpty(mSubPath))
			vPlayer.setSubPath(mSubPath);
		if (mVideoView != null && isInitialized())
			if (!isOpenProgramsList()) {
//				setFullVideoLayout();
				setVideoLayout();
			}else{
				Log.e("loadVPlayerPrefs");
				// 设置窗口大小
				RelativeLayout.LayoutParams Params = (RelativeLayout.LayoutParams) mViewRoot.getLayoutParams();
				Params.height = (int) (/* ScreenHeight */DeviceUtils.getScreenHeight(VideoActivity.this) - getResources().getDimension(R.dimen.tv_programs_list_height));
				Params.width = (int) (/* ScreenWidth */DeviceUtils.getScreenWidth(VideoActivity.this) - getResources().getDimension(R.dimen.tv_programs_list_width));

				mViewRoot.setLayoutParams(Params);

				float windowRatio = Params.width / (float) Params.height;
				// 设置视频画面大小
				int videoWidth = vPlayer.getVideoWidth();
				int videoHeight = vPlayer.getVideoHeight();
				float videoRatio = vPlayer.getVideoAspectRatio();
				LayoutParams VideoViewParams = mVideoView.getLayoutParams();
				
				if(videoWidth  < Params.width * 0.8&& videoHeight  < Params.height * 0.7){
					VideoViewParams.width = (int) ((windowRatio < videoRatio) ? ScreenWidth : (int) (videoRatio * Params.height ));
					VideoViewParams.height = (int) ((windowRatio > videoRatio) ? Params.height : (int) (Params.width / videoRatio ));
					
//					VideoViewParams.width = ((windowRatio < videoRatio) ? (int) (Params.width * 0.9) : (int) (Params.height * windowRatio * 0.9));
//					VideoViewParams.height = (windowRatio > videoRatio) ? (int) (Params.height * 0.9) : (int) (Params.width / videoRatio * 0.9);
					
					mVideoView.setLayoutParams(VideoViewParams);
					mVideoView.getHolder().setFixedSize(videoWidth, videoHeight);
				}
			}
	}

	
	private void setTextViewStyle(OutlineTextView v) {
		v.setTextColor(VP.DEFAULT_SUB_COLOR);
		v.setTypeface(VP.getTypeface(VP.DEFAULT_TYPEFACE_INT), VP.DEFAULT_SUB_STYLE);
		v.setShadowLayer(VP.DEFAULT_SUB_SHADOWRADIUS, 0, 0, VP.DEFAULT_SUB_SHADOWCOLOR);
	}

	private boolean isInitialized() {
		return (mCreated && vPlayer != null && vPlayer.isInitialized());
	}

	private Handler mSubHandler = new Handler() {
		Bundle data;
		String text;
		byte[] pixels;
		int width = 0, height = 0;
		Bitmap bm = null;
		int oldType = SUBTITLE_TEXT;

		@Override
		public void handleMessage(Message msg) {
			data = msg.getData();
			switch (msg.what) {
			case SUBTITLE_TEXT:
				if (oldType != SUBTITLE_TEXT) {
					mSubtitleImage.setVisibility(View.GONE);
					mSubtitleText.setVisibility(View.VISIBLE);
					oldType = SUBTITLE_TEXT;
				}
				text = data.getString(VP.SUB_TEXT_KEY);
				mSubtitleText.setText(text == null ? "" : text.trim());
				break;
			case SUBTITLE_BITMAP:
				if (oldType != SUBTITLE_BITMAP) {
					mSubtitleText.setVisibility(View.GONE);
					mSubtitleImage.setVisibility(View.VISIBLE);
					oldType = SUBTITLE_BITMAP;
				}
				pixels = data.getByteArray(VP.SUB_PIXELS_KEY);
				if (bm == null || width != data.getInt(VP.SUB_WIDTH_KEY) || height != data.getInt(VP.SUB_HEIGHT_KEY)) {
					width = data.getInt(VP.SUB_WIDTH_KEY);
					height = data.getInt(VP.SUB_HEIGHT_KEY);
					bm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
				}
				if (pixels != null)
					bm.copyPixelsFromBuffer(ByteBuffer.wrap(pixels));
				mSubtitleImage.setImageBitmap(bm);
				break;
			}
		}
	};

	private AtomicBoolean mOpened = new AtomicBoolean(Boolean.FALSE);
	private boolean mSurfaceCreated = false;
	private boolean mServiceConnected = false;
	private Object mOpenLock = new Object();
	private static final int OPEN_FILE = 0;
	private static final int OPEN_START = 1;
	private static final int OPEN_SUCCESS = 2;
	private static final int OPEN_FAILED = 3;
	private static final int HW_FAILED = 4;
	private static final int LOAD_PREFS = 5;
	private static final int BUFFER_START = 11;
	private static final int BUFFER_PROGRESS = 12;
	private static final int BUFFER_COMPLETE = 13;
	private static final int CLOSE_START = 21;
	private static final int CLOSE_COMPLETE = 22;
	private static final int SUBTITLE_TEXT = 0;
	private static final int SUBTITLE_BITMAP = 1;
	private static final int OPEN_NEXT = 6;
	private static final int NETWORK_FAILED = 7;
	private static final int OPEN = 8;
	private Handler vPlayerHandler = new Handler() {
		

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case OPEN_FILE:
				Log.e("OPEN_FILE");
				synchronized (mOpenLock) {
					if (!mOpened.get() && vPlayer != null) {
						mOpened.set(true);
						vPlayer.setVPlayerListener(vPlayerListener);
						if (vPlayer.isInitialized())
							mUri = vPlayer.getUri();

						if (mVideoView != null)
							vPlayer.setDisplay(mVideoView.getHolder());
						if (mUri != null)
							vPlayer.initialize(mUri, mDisplayName, mSaveUri, getStartPosition(), vPlayerListener, mParentId, mIsHWCodec);
					}
				}
				break;
			case OPEN_START:
				Log.e("OPEN_START"+mCurrentTitle);
				
				if(!StringUtil.isEmpty(mCurrentTitle)){
					MobclickAgent.onEventEnd(VideoActivity.this, "CHANNEL_VIEW_TIME",mCurrentTitle);
				}
				mVideoLoadingText.setText(getString(R.string.video_layout_loading,getCurrentOnlineVideoTitle(mUri.toString())));
				setVideoLoadingLayoutVisibility(View.VISIBLE);
				break;
			case OPEN_SUCCESS:
				Log.e("OPEN_SUCCESS"+mCurrentTitle);
				if(runnable != null){
					Log.e("每3分钟执行一次runnable："+mCurrentTitle);
					vPlayerHandler.removeCallbacks(runnable);
					vPlayerHandler.postDelayed(runnable, 3*60000);//每3分钟执行一次runnable.
				}
				MobclickAgent.onEventBegin(VideoActivity.this, "CHANNEL_VIEW_TIME", mCurrentTitle);
				loadVPlayerPrefs();
				setVideoLoadingLayoutVisibility(View.GONE);
//				if (!isOpenProgramsList()) {
//					Log.e("OPEN_SUCCESS", "OPEN_SUCCESS");
//					setFullVideoLayout();
//				}else{
//					setVideoLayout();
//				}
				vPlayer.start();
				attachMediaController();
				
				break;
			case OPEN_FAILED:
				Log.e("OPEN_FAILED");
				if(runnable != null){
					Log.e("移除runnable："+mCurrentTitle);
					OpenFailed = true;
					vPlayerHandler.removeCallbacks(runnable);
				}
				String mFailPlayTitle = getCurrentOnlineVideoTitle(mUri.toString());
				MobclickAgent.onEvent(VideoActivity.this, "CHANNEL_PLAYFAIL_COUNT", mFailPlayTitle +":"+mUri.toString());
				mVideoLoadingText.setText(getString(R.string.video_cannot_play,mFailPlayTitle)+ (mNetWorkConnectState == true?"请重试…":"请检查网络设置…"));
				resultFinish(RESULT_FAILED);
				isExternalVideo = false;
				break;
			case BUFFER_START:
				Log.e("BUFFER_START");
				setVideoLoadingLayoutVisibility(View.VISIBLE);
				vPlayerHandler.sendEmptyMessageDelayed(BUFFER_PROGRESS, 1000);
				break;
			case BUFFER_PROGRESS:
				Log.e("BUFFER_PROGRESS");
				if (vPlayer.getBufferProgress() >= 100) {
					setVideoLoadingLayoutVisibility(View.GONE);
				} else {
					mVideoLoadingText.setText(mDownloadRate +"  "+getString(R.string.video_layout_buffering_progress, vPlayer.getBufferProgress()));
					vPlayerHandler.sendEmptyMessageDelayed(BUFFER_PROGRESS, 1000);
					stopPlayer();
				}
				break;
			case BUFFER_COMPLETE:
				Log.e("BUFFER_COMPLETE");
				setVideoLoadingLayoutVisibility(View.GONE);
				vPlayerHandler.removeMessages(BUFFER_PROGRESS);
				break;
			case CLOSE_START:
				Log.e("CLOSE_START");
				mVideoLoadingText.setText(R.string.closing_file);
				setVideoLoadingLayoutVisibility(View.VISIBLE);
				break;
			case CLOSE_COMPLETE:
				mCloseComplete = true;
				break;
			case HW_FAILED:
				if (mVideoView != null) {
					mVideoView.setVisibility(View.GONE);
					mVideoView.setVisibility(View.VISIBLE);
					mVideoView.initialize(VideoActivity.this, VideoActivity.this, false);
				}
				break;
			case LOAD_PREFS:
				loadVPlayerPrefs();
				break;
			case OPEN:
				new VPlayerInitialTask().execute(true);
				break;
			case OPEN_NEXT:
				isExternalVideo = false;
				changeTVProgramsByKey(msg.obj.toString());
				break;
			case NETWORK_FAILED:
				if(isExternalVideo){
					return ;
				}
				if(!mNetWorkConnectState){
					mVideoLoadingText.setText(msg.obj.toString());
					setVideoLoadingLayoutVisibility(View.VISIBLE);
				}
				
				if(vPlayer!= null && mNetWorkConnectState){
					Log.e("vPlayer"+vPlayer.getBufferProgress());
					vPlayer.release();
					vPlayer.releaseContext();
					new VPlayerInitialTask().execute(true);
				}
				break;
			}
		}
	};
	
	Runnable runnable=new Runnable() {
	    @Override
	    public void run() {
	        //频道开启超过三分钟，记录该频道的名称，同时观看次数+1
	    	Log.e("频道开启超过三分钟，记录该频道的名称："+mCurrentTitle);
	    	MobclickAgent.onEvent(VideoActivity.this, "CHANNEL_VIEW_COUNT", mCurrentTitle +":"+mUri.toString());
	    	if (!isInitialized())
	    		return;
	    	vPlayer.setBuffer(5 * 1024 * 1024);
	    	setDefaultLink(mUri.toString());
	    	Log.e("设置缓存："+vPlayer.getBufferProgress());
	    }
	};
	
	private void setVideoLoadingLayoutVisibility(int visibility) {
		if (mVideoLoadingLayout != null && mLoadingProgressView != null) {
			if (visibility == View.VISIBLE)
				mLoadingProgressView.startAnimation(mLoadingAnimation);
			mVideoLoadingLayout.setVisibility(visibility);
		}
	}

	
	private PlayerService.VPlayerListener vPlayerListener = new PlayerService.VPlayerListener() {

		@Override
		public void onHWRenderFailed() {
			if (Build.VERSION.SDK_INT < 11 && mIsHWCodec) {
				vPlayerHandler.sendEmptyMessage(HW_FAILED);
				vPlayerHandler.sendEmptyMessageDelayed(HW_FAILED, 200);
			}
		}

		@Override
		public void onSubChanged(String sub) {
			Message msg = new Message();
			Bundle b = new Bundle();
			b.putString(VP.SUB_TEXT_KEY, sub);
			msg.setData(b);
			msg.what = SUBTITLE_TEXT;
			mSubHandler.sendMessage(msg);
		}

		@Override
		public void onSubChanged(byte[] pixels, int width, int height) {
			Message msg = new Message();
			Bundle b = new Bundle();
			b.putByteArray(VP.SUB_PIXELS_KEY, pixels);
			b.putInt(VP.SUB_WIDTH_KEY, width);
			b.putInt(VP.SUB_HEIGHT_KEY, height);
			msg.setData(b);
			msg.what = SUBTITLE_BITMAP;
			mSubHandler.sendMessage(msg);
		}

		@Override
		public void onOpenStart() {
			vPlayerHandler.sendEmptyMessage(OPEN_START);
		}

		@Override
		public void onOpenSuccess() {
			vPlayerHandler.sendEmptyMessage(OPEN_SUCCESS);
		}

		@Override
		public void onOpenFailed() {
			vPlayerHandler.sendEmptyMessage(OPEN_FAILED);
		}

		@Override
		public void onBufferStart() {
			vPlayerHandler.sendEmptyMessage(BUFFER_START);
			stopPlayer();
		}

		@Override
		public void onBufferComplete() {
			Log.i("VideoActivity#onBufferComplete " + vPlayer.needResume());
			vPlayerHandler.sendEmptyMessage(BUFFER_COMPLETE);
			if (vPlayer != null && !vPlayer.needResume() && !mPlayerStop)
				startPlayer();
		}

		@Override
		public void onPlaybackComplete() {
			// mEnd = true;
			if (mLoopCount == 0 || mLoopCount-- > 1) {
//				 vPlayer.start();
//				 vPlayer.seekTo(0);

				vPlayer.release();
				vPlayer.releaseContext();
				new VPlayerInitialTask().execute(true);
			} else {
				resultFinish(RESULT_OK);
			}

		}

		@Override
		public void onCloseStart() {
			vPlayerHandler.sendEmptyMessage(CLOSE_START);
		}

		@Override
		public void onCloseComplete() {
			vPlayerHandler.sendEmptyMessage(CLOSE_COMPLETE);
		}

		@Override
		public void onVideoSizeChanged(int width, int height) {
//			if (mVideoView != null) {
//				 setVideoLayout();
//			}
		}

		@Override
		public void onDownloadRateChanged(int kbPerSec) {
			mDownloadRate  = String.format("%dKB/s", kbPerSec);
			if (!Media.isNative(mUri.toString()) && mMediaController != null) {
				mMediaController.setDownloadRate(String.format("%dKB/s", kbPerSec));
			}
		}

	};

	





	private void setVideoLayout() {
		if (mVideoView != null) {
			mVideoView.setVideoLayout(mVideoMode, VP.DEFAULT_ASPECT_RATIO, vPlayer.getVideoWidth(), vPlayer.getVideoHeight(), vPlayer.getVideoAspectRatio());
		}
	}

	private void setFullVideoLayout() {
		mVideoView.setVideoLayout(VideoView.VIDEO_LAYOUT_SCALE, VP.DEFAULT_ASPECT_RATIO, vPlayer.getVideoWidth(), vPlayer.getVideoHeight(), vPlayer.getVideoAspectRatio());
	}
	
	private void savePosition() {
		if (mSession != null && vPlayer != null && mUri != null) {
			mSession.put(mUri.toString(), StringHelper.generateTime((int) (0.5 + vPlayer.getCurrentPosition())) + " / " + StringHelper.generateTime(vPlayer.getDuration()));
			if (mEnd)
				mSession.put(mUri + VP.SESSION_LAST_POSITION_SUFIX, 1.0f);
			else
				mSession.put(mUri + VP.SESSION_LAST_POSITION_SUFIX, (float) (vPlayer.getCurrentPosition() / (double) vPlayer.getDuration()));
		}
	}

	private float getStartPosition() {
		if (mFromStart)
			return 1.1f;
		if (mStartPos <= 0.0f || mStartPos >= 1.0f)
			return mSession.getFloat(mUri + VP.SESSION_LAST_POSITION_SUFIX, 7.7f);
		return mStartPos;
	}

	@Override
	public int getBufferPercentage() {
		if (isInitialized())
			return (int) (vPlayer.getBufferProgress() * 100);
		return 0;
	}

	@Override
	public long getCurrentPosition() {
		if (isInitialized())
			return vPlayer.getCurrentPosition();
		return (long) (getStartPosition() * vPlayer.getDuration());
	}

	@Override
	public long getDuration() {
		if (isInitialized())
			return vPlayer.getDuration();
		return 0;
	}

	@Override
	public boolean isPlaying() {
		if (isInitialized())
			return vPlayer.isPlaying();
		return false;
	}

	@Override
	public void pause() {
		if (isInitialized()) {
			vPlayer.stop();
			mPlayerStop = true;
		}

	}

	@Override
	public void seekTo(long arg0) {
		if (isInitialized())
			vPlayer.seekTo((float) ((double) arg0 / vPlayer.getDuration()));
	}

	@Override
	public void start() {
		if (isInitialized()) {
			vPlayer.start();
			mPlayerStop = false;
		}

	}

	@Override
	public void previous() {
	}

	@Override
	public void next() {
	}

	private static final int VIDEO_MAXIMUM_HEIGHT = 2048;
	private static final int VIDEO_MAXIMUM_WIDTH = 2048;

	@Override
	public float scale(float scaleFactor) {
		float userRatio = VP.DEFAULT_ASPECT_RATIO;
		int videoWidth = vPlayer.getVideoWidth();
		int videoHeight = vPlayer.getVideoHeight();
		float videoRatio = vPlayer.getVideoAspectRatio();
		float currentRatio = mVideoView.mVideoHeight / (float) videoHeight;

		currentRatio += (scaleFactor - 1);
		if (videoWidth * currentRatio >= VIDEO_MAXIMUM_WIDTH)
			currentRatio = VIDEO_MAXIMUM_WIDTH / (float) videoWidth;

		if (videoHeight * currentRatio >= VIDEO_MAXIMUM_HEIGHT)
			currentRatio = VIDEO_MAXIMUM_HEIGHT / (float) videoHeight;

		if (currentRatio < 0.5f)
			currentRatio = 0.5f;

		mVideoView.mVideoHeight = (int) (videoHeight * currentRatio);
		mVideoView.setVideoLayout(mVideoMode, userRatio, videoWidth, videoHeight, videoRatio);
		return currentRatio;
	}

	@SuppressLint("SimpleDateFormat")
	@Override
	public void snapshot() {
		// 截图
		if (!FileHelper.sdAvailable()) {
			ToastHelper.showToast(this, R.string.file_explorer_sdcard_not_available);
		} else {
			Uri imgUri = null;
			Bitmap bitmap = vPlayer.getCurrentFrame();
			if (bitmap != null) {
				File screenshotsDirectory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + VP.SNAP_SHOT_PATH);
				if (!screenshotsDirectory.exists()) {
					screenshotsDirectory.mkdirs();
				}

				File savePath = new File(screenshotsDirectory.getPath() + "/" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".jpg");
				if (BitmapHelper.saveBitmapToFile(bitmap, savePath.getPath())) {
					imgUri = Uri.fromFile(savePath);
				}
			}
			if (imgUri != null) {
				sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, imgUri));
				ToastHelper.showToast(this, Toast.LENGTH_LONG, getString(R.string.video_screenshot_save_in, imgUri.getPath()));
			} else {
				ToastHelper.showToast(this, R.string.video_screenshot_failed);
			}
		}
	}

	/**
	 * 判断电视节目列表是否开启
	 */
	private Boolean isOpenProgramsList() {
		int drawerState = mMenuDrawer.getDrawerState();
		if (drawerState == MenuDrawer.STATE_OPEN || drawerState == MenuDrawer.STATE_OPENING) {
			return true;
		} else if (drawerState == MenuDrawer.STATE_CLOSING || drawerState == MenuDrawer.STATE_CLOSED) {
			return false;
		}
		return false;

	}

	/**
	 * 隐藏电视节目列表
	 */
	public void hideProgramsList() {
		// 隐藏节目详细列表
		mTvPrograms.setVisibility(View.GONE);
		// 隐藏电视节目
		mMenuDrawer.closeMenu();
		// 设置窗口大小
		RelativeLayout.LayoutParams Params = (RelativeLayout.LayoutParams) mViewRoot.getLayoutParams();
		Params.height = ScreenHeight;
		Params.width = ScreenWidth;
		mViewRoot.setLayoutParams(Params);

		// 设置视频画面大小
//		setFullVideoLayout();
		setVideoLayout();
	}

	/**
	 * 显示或隐藏电视节目列表
	 */
	public void showORhideProgramsList() {
		if (vPlayer != null && vPlayer.isPlaying()) {
			stopPlayer();
		}
		int drawerState = mMenuDrawer.getDrawerState();
		if (drawerState == MenuDrawer.STATE_OPEN || drawerState == MenuDrawer.STATE_OPENING) {
			// 隐藏电视节目
			mMenuDrawer.closeMenu();
			// 设置窗口大小
			RelativeLayout.LayoutParams Params = (RelativeLayout.LayoutParams) mViewRoot.getLayoutParams();
			Params.height = ScreenHeight;
			Params.width = ScreenWidth;
			mViewRoot.setLayoutParams(Params);

			// 设置视频画面大小
//			setFullVideoLayout();
			setVideoLayout();
			// 隐藏节目列表
			mTvPrograms.setVisibility(View.GONE);

		} else if (drawerState == MenuDrawer.STATE_CLOSING || drawerState == MenuDrawer.STATE_CLOSED) {
			// // 设置窗口大小
			// FrameLayout.LayoutParams Params = (FrameLayout.LayoutParams)
			// mViewRoot
			// .getLayoutParams();
			// Params.height = (int) (/* DeviceUtils.getScreenHeight(this)
			// */ScreenHeight - getResources()
			// .getDimension(R.dimen.tv_programs_list_height));
			// Params.width = (int) (ScreenWidth - getResources().getDimension(
			// R.dimen.tv_programs_list_width));
			//
			// mViewRoot.setLayoutParams(Params);

			// Log.e("Params.height-->" + Params.height + ",Params.width-->"
			// + Params.width);
			// mVideoMode = VideoView.VIDEO_LAYOUT_ORIGIN;
			// setVideoLayout();
			// float windowRatio = Params.width / (float) Params.height;
			// // 设置视频画面大小
			// // mTempMode = mVideoMode;
			// // mVideoMode = VideoView.VIDEO_LAYOUT_SCALE_ZOOM;
			// // scale((float) 0.01);
			// // mVideoMode = mTempMode;
			//
			// int videoWidth = vPlayer.getVideoWidth();
			// int videoHeight = vPlayer.getVideoHeight();
			// float videoRatio = vPlayer.getVideoAspectRatio();
			// LayoutParams lp = mVideoView.getLayoutParams();
			//
			// lp.width = (windowRatio > videoRatio) ? Params.width : (int)
			// (Params.height * windowRatio) ;
			// lp.height = (windowRatio < videoRatio) ? Params.height: (int)
			// (Params.width / videoRatio);
			//
			// //
			// Log.e("videoWidth-->"+videoWidth+",videoHeight-->"+videoHeight+",videoRatio-->"+videoRatio);
			// // Log.e("lp.width-->"+lp.width+",lp.height-->"+lp.height);
			// // // CenterLayout.LayoutParams params = new
			// // CenterLayout.LayoutParams( (int)(ScreenWidth / 2.5),
			// // vPlayer.getVideoHeight() , 0, 0);
			// mVideoView.setLayoutParams(lp);
			//
			// // mVideoView.getHolder().setFixedSize( videoWidth ,
			// videoHeight);
			// //
			// mVideoView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
			// // mVideoView.postInvalidate();
			if(initPrograms){
				NDToast.makeText(VideoActivity.this, R.string.vitamio_init_db, 1000).show();
			}else{
				// 显示电视节目
				mMenuDrawer.toggleMenu(false);
			}
			RelativeLayout.LayoutParams ProgramsListParams = (RelativeLayout.LayoutParams) mTvPrograms.getLayoutParams();
			if (ProgramsListParams.width != mMenuWidth) {
				ProgramsListParams.height = (int) getResources().getDimension(R.dimen.tv_programs_list_height);
				ProgramsListParams.width = (int) (ScreenWidth - getResources().getDimension(R.dimen.tv_programs_list_width));

				mTvPrograms.setLayoutParams(ProgramsListParams);
			}
			// 显示节目列表ʾ
			mTvPrograms.setVisibility(View.VISIBLE);
			// mMenuDrawer.getContentContainer().requestLayout();
		}
		startPlayer();
//		mTabContent.requestFocus();
	}

	@Override
	public void toggleVideoMode(int mode) {
		final int drawerState = mMenuDrawer.getDrawerState();
		if (drawerState == MenuDrawer.STATE_OPEN || drawerState == MenuDrawer.STATE_OPENING) {
			return;
		}
		mVideoMode = mode;
		setVideoLayout();
	}

	@Override
	public void stop() {
		onBackPressed();
	}

	@Override
	public long goForward() {
		return 0;
	}

	@Override
	public long goBack() {
		return 0;
	}

	@Override
	public void removeLoadingView() {
		mVideoLoadingLayout.setVisibility(View.GONE);
	}

	@Override
	public void onSurfaceCreated(SurfaceHolder holder) {
		Log.i("onSurfaceCreated");
		mSurfaceCreated = true;
		if (mServiceConnected)
			vPlayerHandler.sendEmptyMessage(OPEN_FILE);
		if (vPlayer != null)
			vPlayer.setDisplay(holder);
	}

	@Override
	public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		if (vPlayer != null) {
			vPlayer.setDisplay(holder);
			if (!isOpenProgramsList()) {
				Log.e("onSurfaceChanged");
//				setFullVideoLayout();
				setVideoLayout();
			} else {
//				setFullVideoLayout();
				Log.e("onSurfaceChanged");
				// 设置窗口大小
//				RelativeLayout.LayoutParams Params = (RelativeLayout.LayoutParams) mViewRoot.getLayoutParams();
//				Params.height = (int) (/* ScreenHeight */DeviceUtils.getScreenHeight(VideoActivity.this) - getResources().getDimension(R.dimen.tv_programs_list_height));
//				Params.width = (int) (/* ScreenWidth */DeviceUtils.getScreenWidth(VideoActivity.this) - getResources().getDimension(R.dimen.tv_programs_list_width));
//
////				mViewRoot.setLayoutParams(Params);
//
//				float windowRatio = Params.width / (float) Params.height;
//				// 设置视频画面大小
//				// mTempMode = mVideoMode;
//				// mVideoMode = VideoView.VIDEO_LAYOUT_SCALE_ZOOM;
//				// scale((float) 0.01);
//				// mVideoMode = mTempMode;
//
//				int videoWidth = vPlayer.getVideoWidth();
//				int videoHeight = vPlayer.getVideoHeight();
//				float videoRatio = vPlayer.getVideoAspectRatio();
//				LayoutParams lp = mVideoView.getLayoutParams();
//
//				if(videoWidth < Params.width && videoHeight < Params.height){
//					lp.width = Params.width;
//					lp.height = Params.height;
//					mVideoView.setLayoutParams(lp);
//				}
//				Log.e("windowRatio-->" + windowRatio + ",videoRatio-->" + videoRatio);
//				lp.width = ((windowRatio < videoRatio) ? (int) (Params.width * 0.9) : (int) (Params.height * windowRatio * 0.9));
//				lp.height = (windowRatio > videoRatio) ? (int) (Params.height * 0.9) : (int) (Params.width / videoRatio * 0.9);
				// Log.e("videoWidth-->"+videoWidth+",videoHeight-->"+videoHeight+",videoRatio-->"+videoRatio);
				// Log.e("lp.width-->"+lp.width+",lp.height-->"+lp.height);

				
			}
		}
	}

	@Override
	public void onSurfaceDestroyed(SurfaceHolder holder) {
		Log.i("onSurfaceDestroyed");
		if (vPlayer != null && vPlayer.isInitialized()) {
			if (vPlayer.isPlaying()) {
				vPlayer.stop();
				vPlayer.setState(PlayerService.STATE_NEED_RESUME);
			}
			vPlayer.releaseSurface();
			if (vPlayer.needResume())
				vPlayer.start();
		}
	}

	private class VPlayerInitialTask extends AsyncTask<Boolean, Object, Object> {

		@Override
		protected void onPreExecute() {
			try {
//				VideoActivity.this.mVideoView.setVisibility(8);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override
		protected Object doInBackground(Boolean... arg0) {
			try {
				if (!vPlayer.initialize(mUri, mDisplayName, mSaveUri, getStartPosition(), vPlayerListener, mParentId, mIsHWCodec)) {
					VideoActivity.this.mPlayerOK = true;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Object result) {
			try {
				if (VideoActivity.this.mPlayerOK) {
					VideoActivity.this.mVideoView.setVisibility(0);
					VideoActivity.this.mPlayerOK = false;
				}
				return;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	public void goToNext(String CurrentSourcrNum) {
		try {
			isExternalVideo = false;
			UpDownflag = false;
			if (isOpenProgramsList()) {
				String GoToLink = changeTVProgram(CurrentSourcrNum, 0);
				if (StringUtil.isEmpty(GoToLink)) {
					QueryBuilder<OnlineVideoSource,Integer> preparedQuery = OnlineVideoSourceDao.queryBuilder();
					preparedQuery.where().eq("sourcenum", CurrentSourcrNum);
					OnlineVideoSource OnlineVideoSource = OnlineVideoSourceDao.queryForFirst(preparedQuery.prepare());
					if(OnlineVideoSource != null && !StringUtil.isEmpty(OnlineVideoSource.getLink())){
						GoToLink = OnlineVideoSource.getLink();
					}
				}

				if (!mUri.equals(Uri.parse(GoToLink)) || OpenFailed) {
					vPlayerHandler.sendEmptyMessage(OPEN_START);
					hideProgramsList();
					OpenFailed = false;
					stopPlayer();
					VideoActivity.this.mVideoView.setVisibility(8);
					mUri = Uri.parse(GoToLink);
					new VPlayerInitialTask().execute(new Boolean[0]);
				
					// String mCurrentSourcenum =OnlineVideoSourceDao.queryData("SELECT * FROM ONLINEVIDEOSOURCE WHERE link = '"+ mUri.toString() + "' limit 0,1").getSourcenum();
					// changeTVProgram(CurrentSourcrNum,0);

				} else {
					// 隐藏电视节目
					mMenuDrawer.closeMenu();
				}
			} else {
				// 显示电视节目
				// mMenuDrawer.toggleMenu(false);
				// 为了显示完全节目表
				showORhideProgramsList();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

//	public void goToNext(String path) {
//		try {
//			isExternalVideo = false;
//			if (isOpenProgramsList()) {
//				if(!mUri.equals(Uri.parse(path)) || OpenFailed){
//					vPlayerHandler.sendEmptyMessage(OPEN_START);
//					hideProgramsList();
//					OpenFailed = false;
//					stopPlayer();
//					VideoActivity.this.mVideoView.setVisibility(8);
//					mUri = Uri.parse(path);
//					new VPlayerInitialTask().execute(new Boolean[0]);
//					
//					String mCurrentSourcenum = OnlineVideoSourceDao.queryData("SELECT * FROM ONLINEVIDEOSOURCE WHERE link = '" + mUri.toString() + "' limit 0,1").getSourcenum();
//					changeTVProgram(mCurrentSourcenum,0);
//					
//				}else{
//					// 隐藏电视节目
//					mMenuDrawer.closeMenu();
//				}
//			} else {
//				// 显示电视节目
////			mMenuDrawer.toggleMenu(false);
//				//为了显示完全节目表
//				showORhideProgramsList();
//			}
//		} catch (SQLException e) {
//			e.printStackTrace();
//		}
//}
	/**
	 * 显示节目预告信息
	 * @param ProgramsList
	 */
	@SuppressLint("SimpleDateFormat")
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void showProgramsList(List ProgramsList) {
		if(isOpenProgramsList()){
			if(ProgramsList != null && ProgramsList.size() > 0 ){
				// 隐藏节目列表ʾ
				mTvProgramsGridview.setVisibility(View.VISIBLE);
				mTvProgramsTextView.setVisibility(View.GONE);
				TVProgram mCurrentTVProgram = OnlineTVParser.getInstance().getCurrentTVProgram(ProgramsList, new Date());
				
				SimpleDateFormat simpleDateParser = new SimpleDateFormat(
						DateUtil.DEFAULT_DATE_PARSE);
				String today = simpleDateParser.format(new Date())/*"2013-03-17 16:50:00"*/;
				List mProgramsList = new ArrayList<TVProgram>();
				for(int i = 0,x = ProgramsList.size() ;i < ProgramsList.size();i++){
					String dateStr = ((TVProgram) ProgramsList.get(i)).getPlayTime();
					if((x + mProgramsList.size())> 21){
						if(today.compareTo(dateStr)<0){
							mProgramsList.add((TVProgram) ProgramsList.get(i));
						}
					}else{
						mProgramsList.add((TVProgram) ProgramsList.get(i));
					}
					x--;
				}
				mTVProgramsListDescAdapter = new TVProgramsGridViewDescAdapter(this, mProgramsList, mCurrentTVProgram);
				mTvProgramsGridview.setAdapter(mTVProgramsListDescAdapter);
				mTvProgramsGridview.setFocusable(false);
			}else{
				// 隐藏节目列表
				mTvProgramsTextView.setVisibility(View.VISIBLE);
				mTvProgramsGridview.setVisibility(View.GONE);
			}
		}
	}

	public void reshData(int index) {
		mTabTVPagerAdapter.notifyDataSetChanged();
		mTabTVPager.setCurrentItem(index);
	}
	
	/**
	 * 判断网络是否可用
	 * 
	 * @return
	 */
	protected boolean checkNetworkAvailable() {
		boolean flag = false;
		ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cwjManager.getActiveNetworkInfo() != null) {
			flag = cwjManager.getActiveNetworkInfo().isAvailable();
		}
		return flag;
	}
	

	
	/**
     * 监听网络连接状态Receiver
     * 
     * @author admin
     * 
     */
	private BroadcastReceiver NetworkStateReceiver  = new BroadcastReceiver() {
		

		@Override
		public void onReceive(Context context, Intent intent) {
			NetworkInfo mNetworkInfo = null;
			State state = State.UNKNOWN;
			Log.e("网络状态改变");   
			boolean success = false;   
			//获得网络连接服务   
			ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);   
			// State state = connManager.getActiveNetworkInfo().getState();
			//获取Wi-Fi网络连接状态   
			mNetworkInfo= connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
				if(mNetworkInfo != null ){
					state = mNetworkInfo.getState(); 
					//判断是否正在使用WIFI网络   
					if (State.CONNECTED == state) { 
						//网络为已连接状态
						success = true;  
						System.out.println("Wi-Fi网络连接");
						mNetWorkConnectState = true;
						//Toast.makeText(mContext, "Wi-Fi网络连接", Toast.LENGTH_LONG).show();
					}   
			}
				
			 //获取GPRS网络连接状态   
			mNetworkInfo= connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
				if(mNetworkInfo != null ){
					state = mNetworkInfo.getState();
					//判断是否正在使用GPRS网络   
					if (State.CONNECTED == state) { 
						//网络为已连接状态
						success = true;   
						mNetWorkConnectState = true;
						System.out.println("GPRS网络连接");
						//Toast.makeText(mContext, "GPRS网络连接", Toast.LENGTH_LONG).show();
				}   
			}
				
			//获取以太网网络连接状态   
			mNetworkInfo= connManager.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);
				if(mNetworkInfo != null ){
					state = mNetworkInfo.getState(); 
					//判断是否正在使用以太网网络   
					if (State.CONNECTED == state) { 
						//网络为已连接状态
						success = true;   
						mNetWorkConnectState = true;
						System.out.println("以太网网络连接");
					}   
			}
			if (!success) {  
				mNetWorkConnectState = false;
				System.out.println("您的网络连接已中断");
				mPlayerStop = true;
				Message message= vPlayerHandler.obtainMessage(NETWORK_FAILED);
				message.obj = "网络连接中断，请检查网络设置…";
				vPlayerHandler.sendMessageDelayed(message,10 * 1000);
				return;
			} 
			else{
				if(vPlayer!= null && mNetWorkConnectState ){
					if(mPlayerStop){
						System.out.println("连接状态:" + getAPNType());
						vPlayer.release();
						vPlayer.releaseContext();
						new VPlayerInitialTask().execute(true);
						mPlayerStop = false;
					}
				}
			}				
			
		}
	};
	
	/**
	 * 获取当前的网络状态  -1:没有网络、1:WIFI网络、2:wap网络、3:net网络
	 * @return
	 */
	public int getAPNType(){ 
		int netType = -1;  
		ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); 
		if(networkInfo == null){ 
			return netType; 
		} 
		int nType = networkInfo.getType(); 
		if(nType == ConnectivityManager.TYPE_MOBILE){ 
			Log.e("networkInfo.getExtraInfo()", "networkInfo.getExtraInfo() is "+networkInfo.getExtraInfo()); 
			if(networkInfo.getExtraInfo().toLowerCase().equals("cmnet")){ 
				netType = /*CMNET*/2;
			} else{ 
				netType = /*CMWAP*/3;
			} 
		} else if(nType==ConnectivityManager.TYPE_WIFI){ 
			netType = /*WIFI*/1; 
		} 
		return netType; 
	} 
	
	
	/**
	 * ping接网络地址
	 * @param str
	 * @return
	 */
	public boolean pingHost(String str){
		//是否连接上网络(true:连接   false:未连接)
		boolean resaultBool = false;  
        try {  
            //Hardcoded for now, make it UI configurable   
            Process p = Runtime.getRuntime().exec("ping -c 1 -w 100 " +str);  
            int status = p.waitFor();  
            if (status == 0) {  
                //resault="success";
            	resaultBool = true;
            } else {  
                //resault="faild";
            	resaultBool = false;
            }  
        } catch (IOException e) {   
        	Log.e("ping 网络发生异常.."+ e);
        } catch (InterruptedException e) {    
        	Log.e("ping 网络发生异常.."+e);
        }  
        return resaultBool;  
    }
	
	/**
	 * 启动网络状态监听
	 */
	public void startNetworkListener() {
		//启动线程监听网络状态
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					try {
						long a = System.currentTimeMillis();
						//ping网络,判断网络是否连接到外网.
						boolean connectNetworkBool  = pingHost("baidu.com");
						Log.e("网络连接状态::->" + connectNetworkBool);
						if (connectNetworkBool) {
							Log.e("已连接广播");
							mNetWorkConnectState = true;
							if(mPlayerStop){
								Log.e("网络连接成功…");
								Message message= vPlayerHandler.obtainMessage(NETWORK_FAILED);
								message.obj = "网络连接成功…";
								vPlayerHandler.removeMessages(NETWORK_FAILED);
								vPlayerHandler.sendMessageDelayed(message,10 * 1000);
								mPlayerStop = false;
							}
						} else {
								Log.e("断开连接广播");
								mNetWorkConnectState = false;
								if(runnable != null){
									OpenFailed = true;
									vPlayerHandler.removeCallbacks(runnable);
								}
								if(!mPlayerStop){
									Log.e("断开连接…");
									mPlayerStop = true;
									Message message= vPlayerHandler.obtainMessage(NETWORK_FAILED);
									message.obj = "网络连接受限,请检查网络设置…";
									vPlayerHandler.removeMessages(BUFFER_PROGRESS);
									vPlayerHandler.removeMessages(NETWORK_FAILED);
									vPlayerHandler.sendMessageDelayed(message,10 * 1000);
								}
							}
						Log.e("ping服务时间:"+ (System.currentTimeMillis() - a) / 1000 +"s");
						//休眠10秒
						Thread.sleep(10 * 1000);
					} catch (Exception e) {
						Log.e("Exception", e);
					}
				}
			}
		}).start();
	}
	
	private class NetWorkTask extends AsyncTask<String, Object, Boolean> {

		@Override
		protected void onPreExecute() {
			
		}

		@Override
		protected Boolean doInBackground(String... params) {
			return pingHost("baidu.com");
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (result) {
				//发生网络已连接广播
				Log.e("网络连接状态::->" + result);
				 
			} else {
				mNetWorkConnectState = false;
				//发生网络断开连接广播
				vPlayerHandler.sendEmptyMessage(NETWORK_FAILED);
				Log.e("网络连接状态::->" + result);
			}
		}
	}
	
	/**
	 * Restart the application.
	 */
	public void restartApplication() {
		PendingIntent intent = PendingIntent.getActivity(this.getBaseContext(), 0, new Intent(getIntent()), getIntent().getFlags());
		AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, intent);
		System.exit(2);
	}
}
